package mamikeji.liaowa.ui.activity.article;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import mamikeji.liaowa.R;
import mamikeji.liaowa.bean.ArticleListBean;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.ui.activity.BaseActivity;
import mamikeji.liaowa.ui.adapter.Article_ListAdapter;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MultiStateView;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshBase;
import mamikeji.liaowa.widget.pulltorefresh.PullToRefreshListView;
import mamikeji.liaowa.widget.refreshView.PtrlDownRefreshFrameLayout;

public class Article_ListActivity extends BaseActivity {
    private static final String TAG = "Article_ListActivity";
    private static final int TAG_CIRCLE = 1001;
    private PtrlDownRefreshFrameLayout ptrlDownRefreshFrameLayout_article_list;
    private PullToRefreshListView listView_day_article_date;
    private MultiStateView multiStateView_article_date;
    private String category;//文章类别

    private List<ArticleListBean.DataEntity> dataEntityList = new ArrayList<>();

    private Article_ListAdapter article_listAdapter;

    private int page = 1;
    private int maxPage = 0;
    private List<ArticleListBean.DataEntity> mList;

    Boolean bool_circle_refresh = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_day_article);
        getBase();
        ButterKnife.bind(this);
        Intent intent = getIntent();
        category = intent.getStringExtra("category");

        setTitleLeftImage(R.drawable.icon_fanhuibai_n_fff, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bool_circle_refresh){
                    setResult(RESULT_OK, new Intent());
                }
                finish();
            }
        });
        setTitleName(intent.getStringExtra("category_name"));
        getListviewTop(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ((System.currentTimeMillis() - timeTop) > 200) {
                    timeTop = System.currentTimeMillis();
                } else {
                    timeTop = 0;
                    listView_day_article_date.getRefreshableView().setSelection(0);
                }
            }
        });

        article_listAdapter = new Article_ListAdapter(dataEntityList, this);
        ptrlDownRefreshFrameLayout_article_list = (PtrlDownRefreshFrameLayout) findViewById(R.id.ptrlDownRefreshFrameLayout_article_list);
        listView_day_article_date = (PullToRefreshListView) findViewById(R.id.listView_day_article_date);
        listView_day_article_date.setAdapter(article_listAdapter);

        multiStateView_article_date = (MultiStateView) findViewById(R.id.multiStateView_article_date);

        listView_day_article_date.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(Article_ListActivity.this, Article_DetailsActivity.class);
                intent.putExtra("articleId", dataEntityList.get(i - 1).getArticleId() + "");
                startActivityForResult(intent, TAG_CIRCLE);
            }
        });

        initDate(1, 10);

        multiStateView_article_date.getView(MultiStateView.VIEW_STATE_ERROR).findViewById(R.id.button_error_refish)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        multiStateView_article_date.setViewState(MultiStateView.VIEW_STATE_LOADING);
                        initDate(1, 10);
                    }
                });

        ptrlDownRefreshFrameLayout_article_list.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, listView_day_article_date.getRefreshableView(), header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                initDate(1, 10);
            }
        });
        listView_day_article_date.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        listView_day_article_date.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            //下拉刷新数据
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

            }

            //上拉加载更多
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                initDate(++page, 10);
            }
        });
    }

    /**
     * 获取文章列表
     */
    private void initDate(final int indexpage, int num) {
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.ARTICLE_TYPE_LIST_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.ARTICLE_TYPE_LIST_CATEGORY, category);
        formMap.put(HttpKey.ARTICLE_TYPE_LIST_PAGE, "" + indexpage);
        formMap.put(HttpKey.ARTICLE_TYPE_LIST_PAGESIZE, "" + num);
        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.ARTICLE_TYPE_LIST, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                multiStateView_article_date.setViewState(MultiStateView.VIEW_STATE_NOINTERNET);
                listView_day_article_date.onRefreshComplete();
                ptrlDownRefreshFrameLayout_article_list.refreshComplete();
            }

            @Override
            public void onResponse(String response) {
                ForLog.i(TAG, response);
                listView_day_article_date.onRefreshComplete();
                ptrlDownRefreshFrameLayout_article_list.refreshComplete();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        ArticleListBean articleListBean = new Gson().fromJson(response, ArticleListBean.class);
                        if (articleListBean.getData().size() > 0) {
                            mList = new ArrayList<ArticleListBean.DataEntity>();
                            mList = articleListBean.getData();

                            if (mList.size() <= 0) {
                                new Handler().postDelayed(new Runnable(){
                                    public void run() {
                                        listView_day_article_date.onRefreshComplete();
                                    }
                                }, 1000);
                                ForToast.showToast(R.string.error_down_end);
                            } else {
                                if (indexpage == 1){
                                    dataEntityList.clear();
                                    dataEntityList.addAll(mList);
                                    article_listAdapter.setList(dataEntityList);
                                }else {
                                    dataEntityList.addAll(mList);
                                    article_listAdapter.notifyDataSetChanged();
                                }
                            }
                            multiStateView_article_date.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            if (indexpage==1){
                                multiStateView_article_date.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                            }else {
                                multiStateView_article_date.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                            }
                        }
                    } else {
                        multiStateView_article_date.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == TAG_CIRCLE) {
                bool_circle_refresh = true;
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (bool_circle_refresh){
                setResult(RESULT_OK, new Intent());
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
